var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var user = require('../../utils/user.js');


var app = getApp();
var mark = "0"

Page({
  data: {
    footprintList: [],  // 设备列表
    slotList:[],  // 卡槽列表
    page: 1,
    limit: 10,
    totalPages: 1,
    hasLogin: false,    
    slotWin:false,  // 卡槽设置窗口    
    materialWin:false,  // 原料选择 窗口    
    slotItems:[],  // 卡槽设置数据
    materialList:[],  // 原料列表数据
    currentDevid:"", // 当前设备id
    currentSlotIndex:"", // 当前卡槽
    mark:false,

    productWin:false,  // 商品选择窗口
    productActiveIndex:0, // 分类已选择
    productActiveId:[], // 商品已选择
    // 商品数据
    productItems:[]
  },

  onClickNav({ detail = {} }) {
    this.setData({
      productActiveIndex: detail.index || 0,
    });
  },

  onClickItem({ detail = {} }) {
    const { productActiveId } = this.data;
    const index = productActiveId.indexOf(detail.id);
    if (index > -1) {
      productActiveId.splice(index, 1);
    } else {
      productActiveId.push(detail.id);
    }

    this.setData({ productActiveId });
    console.log(productActiveId)
  },
  // 选商品
  showProductWin(obj) {
    console.log(obj)
    this.getProductList()    
    // 已选商品
    this.getDevGoodsList(obj.currentTarget.id)
    this.setData({ 
      productWin: true,
      currentDevid:obj.currentTarget.id
     });
  },
  // 选卡槽
  showSlotWin(obj) {
    console.log(obj.currentTarget.id)
    this.getSlotList(obj.currentTarget.id)
      this.setData({ 
        slotWin: true ,
        currentDevid:obj.currentTarget.id
      });
  },
  // 选卡槽 - 选原料
  showMaterialWin(obj) {

    this.getMaterialList()
      this.setData({ 
        materialWin: true,
        currentSlotIndex:obj.currentTarget.id
      });
  },
  // 关闭商品绑定窗口
  closeProductWin(e) {
    console.log(e)
    var that=this
    // 区分点击按及背景
    if(e.type==="click-overlay"){
      mark="1"
    }
    setTimeout(function(){ 
        mark=0
     },1000)
    //  点背景
      if(mark==="1"){
        that.setData({ 
          productWin: false 
        });
        return false
      }
      // 点确定按钮
      this.UpdateDevGoods()
      console.log('closeProductWin')
      mark=0
      that.setData({ 
        productWin: false 
      });
    
  },
   // 关闭卡槽绑定窗口
  closeSlotWin(e) {
    console.log(e)
    var that=this
    // 区分点击按及背景
    if(e.type==="click-overlay"){
      mark="1"
    }
    setTimeout(function(){ 
        mark=0
     },1000)
    //  点背景
      if(mark==="1"){
        that.setData({ 
          slotWin: false 
        });
        return false
      }
      // 点确定按钮
      this.submitMaterial()
    this.setData({ slotWin: false });
  },
  // 关闭原料选择
  closeMaterialWin() {
    this.setData({ materialWin: false });
  },
  goLogin: function(e) {
      if (e.detail.userInfo == undefined) {
        app.globalData.hasLogin = false;
        util.showErrorToast('微信登录失败');
        return;
      } 
        var that=this
     
        wx.setStorageSync('userInfo', e.detail.userInfo);
       
              
            console.log('.. dev')  

        
    wx.navigateTo({
      url: "/pages/auth/login/login"
    });
  },
  getFootprintList() {
    wx.showLoading({
      title: '加载中...',
    });
    let that = this;
    util.request(api.DevList, {
      page: 1,
      limit: 10000
    }).then(function(res) {
      if (res.errno === 0) { 
        that.setData({
          footprintList:  res.data,
          totalPages: 1
        });
        
      }
      wx.hideLoading();
        console.log( that.footprintList)
    });
    
  },
  // 产品列表
  getProductList(devId) {
    let that = this;
    util.request(api.GoodsList, {
      page: 1,
      limit: 10000
    }).then(function(res) {
      if (res.errno === 0) { 
        that.setData({
          productItems:  res.data
        });
        
      }
    });    
  },
  // 设备绑定产品
  UpdateDevGoods() {
    const devId=this.data.currentDevid+''
    const ids=this.data.productActiveId
    util.request(api.UpdateDevGoods, {
      goodsVoList: [{
        "devId": devId,
        "goodsId": ids
      }]
    }, 'POST').then(function(res) {
      this.setData({ productWin: true });
    });   
  },
  // 设备已绑定产品列表
  getDevGoodsList(devId) {
    let that = this;
    util.request(api.DevGoodsList, {
      devId: devId
    }).then(function(res) {
      if (res.errno === 0) { 
        that.setData({
          productActiveId:  Array.from(res.data, (v) => v.id)
        });
        
      }
    });    
  },
  // 卡槽列表
  getSlotList(devId) {
    let that = this;
    util.request(api.SlotList, {
      devId: devId
    }).then(function(res) {
      if (res.errno === 0) { 
        that.setData({
          slotList:  res.data
        });
        
      }
    });    
  },
  // 原料列表
  getMaterialList() {
    let that = this;
    util.request(api.MaterialList,{
      page: 1,
      limit: 10000
    }).then(function(res) {
      if (res.errno === 0) { 
        const tmplist=util.objReplace(res.data.list,{'name':'text','code':'value'})
        that.setData({
          materialList: tmplist
        });
        
      }
    });    
  },
  // 原料确认选择
  confirmMaterial(event) {
    const { picker, value, index } = event.detail; 
    var preList= util.objAddKey(this.data.slotList,{'devId':this.data.currentDevid})
    preList[this.data.currentSlotIndex].materialId= value.id,
    preList[this.data.currentSlotIndex].materialName= value.text 
    this.setData({
      slotList: preList
    });
    console.log(this.data.slotList)
    this.closeMaterialWin()
  },

  // 原料确认选择
  submitMaterial(event) {    
    let that = this;
    util.request(api.UpdateDevSlot,{
      devMaterialSlots: this.data.slotList
    }, 'POST').then(function(res) {
      if (res.errno === 0) { 
        that.closeSlotWin()
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 3000
        });
      }
    });    
  },
  deleteItem(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let iindex = event.currentTarget.dataset.iindex;
    let footprintId = this.data.footprintList[index][iindex].id;
    let goodsId = this.data.footprintList[index][iindex].goodsId;
    var touchTime = that.data.touchEnd - that.data.touchStart;
    console.log(touchTime);
    //如果按下时间大于350为长按  
    if (touchTime > 350) {
      wx.showModal({
        title: '',
        content: '要删除所选足迹？',
        success: function(res) {
          if (res.confirm) {
            util.request(api.FootprintDelete, {
              id: footprintId
            }, 'POST').then(function(res) {
              if (res.errno === 0) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000
                });
                that.data.footprintList[index].splice(iindex, 1)
                if (that.data.footprintList[index].length == 0) {
                  that.data.footprintList.splice(index, 1)
                }
                that.setData({
                  footprintList: that.data.footprintList
                });
              }
            });
          }
        }
      });
    } else {
      wx.navigateTo({
        url: '/pages/goods/goods?id=' + goodsId,
      });
    }

  },
  onLoad: function(options) {
  },
 /*  onReachBottom() {
    if (this.data.totalPages > this.data.page) {
      this.setData({
        page: this.data.page + 1
      });
      this.getFootprintList();
    } else {
      wx.showToast({
        title: '没有更多了',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
  }, */
  onReady: function() {

  },
  onShow: function() {
    var userInfo=wx.getStorageSync('userInfo');
    // 跳过手机绑定
     if(!userInfo.mobile || userInfo.mobile.length<11){
      console.log('checkLogin-------nnnnnnnnnnnooooooooooo-------')
      console.log(userInfo)
      this.setData({
        hasLogin: false
      });
    }else{
      user.checkLogin().then(() => {
        console.log('checkLogin--------------')
        // 页面显示
        if (app.globalData.hasLogin) {
          this.getFootprintList();
        }
  console.log(app.globalData.hasLogin)
        this.setData({
          hasLogin: app.globalData.hasLogin
        });
        console.log(this.data.hasLogin)
      })
    }

    //  user.checkLogin().then(() => {
    // })
    

  },
  onHide: function() {
    // 页面隐藏

  },
  onUnload: function() {
    // 页面关闭
  },
  //按下事件开始  
  touchStart: function(e) {
    let that = this;
    that.setData({
      touchStart: e.timeStamp
    })
    console.log(e.timeStamp + '- touchStart')
  },
  //按下事件结束  
  touchEnd: function(e) {
    let that = this;
    that.setData({
      touchEnd: e.timeStamp
    })
    console.log(e.timeStamp + '- touchEnd')
  },
})